// src/router/index.js（Vue 2 写法）
import Vue from 'vue'
import VueRouter from 'vue-router'
import UserLogin from '../components/UserLogin.vue'
import UserHome from '../components/UserHome.vue'
import WelcomePage from '../components/WelcomePage.vue'
import UsersPage from '../components/user/UsersPage.vue'
import UserRights from '../components/power/UserRights.vue'
import UserRoles from '../components/power/UserRoles.vue'
import UserCate from '../components/goods/UserCate.vue'
import UserParams from '../components/goods/UserParams.vue'
import UserList from '../components/goods/UserList.vue'
import UserAdd from '../components/goods/UserAdd.vue'
import UserOrder from '../components/order/UserOrder.vue'
import UserReport from '../components/report/UserReport.vue'
Vue.use(VueRouter) // 安装路由插件

const routes = [
  {
    path: '/Home',
    name: 'Home',
    component: UserHome,
    meta: { requiresAuth: true },
    children: [
      {
        path: '', // 空路径（匹配根路由 `/`）
        redirect: 'welcome', // 重定向到子路由 `welcome`
        meta: { requiresAuth: true }
      },
      {
        path: '/login',
        name: 'UserLogin',
        component: UserLogin,
        meta: { requiresAuth: false }
      },
      {
        path: 'welcome',
        name: 'WelcomePage',
        component: WelcomePage,
        meta: { requiresAuth: true }
      },
      {
        path: '/users',
        name: 'UsersPage',
        component: UsersPage,
        meta: { requiresAuth: true }
      },
      {
        path: '/rights',
        name: 'UserRights',
        component: UserRights,
        meta: { requiresAuth: true }
      },
      {
        path: '/roles',
        name: 'UserRoles',
        component: UserRoles,
        meta: { requiresAuth: true }
      },
      {
        path: '/categories',
        name: 'UserCate',
        component: UserCate,
        meta: { requiresAuth: true }
      },
      {
        path: '/params',
        name: 'UserParams',
        component: UserParams,
        meta: { requiresAuth: true }
      },
      {
        path: '/goods',
        name: 'UserList',
        component: UserList,
        meta: { requiresAuth: true }
      },
      {
        path: '/goods/add',
        name: 'UserAdd',
        component: UserAdd,
        meta: { requiresAuth: true }
      },
      {
        path: '/orders',
        name: 'UserOrder',
        component: UserOrder,
        meta: { requiresAuth: true }
      },
      {
        path: '/reports',
        name: 'UserReport',
        component: UserReport,
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash', // 使用 hash 模式（默认）
  routes
})

// 路由守卫：验证登录状态
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !window.sessionStorage.getItem('token')) {
    next('/login') // 未登录则跳转登录页
  } else {
    next()
  }
})

export default router
